const net = require('net')
const { deflate } = require('zlib')
const server = net.createServer()


const clients = []


server.on('connection', clientSocket => {
    
    console.log('新连接来了.')
    
    // 群发收到的消息
    clientSocket.on('data',data => {
        data = JSON.parse(data.toString().trim())

        switch (data.type) {
            // 创建房间 {type,username}
            case "new":
                // 创建房间并通知用户创建成功
                clients.push([data.username,clientSocket,data.mode])
                clientSocket.write('new successfully')
                console.log("用户"+data.username+"创建了房间.")
                break

            // 加入房间 {type,from,to}    
            case "join":          
                // 是否加入成功       
                let sucess = false

                // 找到data.to
                clients.forEach( client => {
                    if(client[0] == data.to && !sucess) {
                        client.push(data.from)
                        client.push(clientSocket)
                        // 通知用户data.from已加入房间
                        client[1].write("1:"+data.from)
                        
                        // 加入房间成功
                        clients.push([data.from,clientSocket,client[2],data.to,client[1]])
                        clientSocket.write(client[2] + ' join successfully')
                        sucess = true
                        console.log("用户"+data.from+"加入了"+ data.to + "的房间.")
                    }
                })
                // 加入房间失败
                if(!sucess){
                    clientSocket.write('join failed')
                }
                break

            // 发送分数 {type,score,username}
            case "score":
                // 将分数发给另一位
                clients.forEach( client => {
                    if(client[0] == data.username) {
                        client[4].write(data.score)
                        console.log("用户"+data.username+"发送分数"+ data.score + "给了"+ client[3])
                    }
                })
                break

            // 无效信息
            default:
                clientSocket.write('invalid message')
                break
        }        
    })
})

server.listen(3008, () => console.log('server run...'))
